package com.asia.execl;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import com.asia.domain.ods.OdsTable;
import com.util.HibernateUtil;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class ExcelExport<T> {
    //��ʽ������  
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @SuppressWarnings("unchecked")
    public void exportExcel(String title, Collection<T> dataset, OutputStream out) {
        // ����һ�������� 
        try {
            //���ȼ����ݿ��Ƿ�����ȷ��  
            Iterator<T> iterator = dataset.iterator();
            if (dataset == null || !iterator.hasNext() || title == null || out == null) {
                throw new Exception("�������ݲ��ԣ�");
            }
            //ȡ��ʵ�ʷ�����  
            T tObject = iterator.next();
            Class<T> clazz = (Class<T>) tObject.getClass();

            HSSFWorkbook workbook = new HSSFWorkbook();
            // ���һ�����  
            HSSFSheet sheet = workbook.createSheet(title);
            // ���ñ��Ĭ���п��Ϊ20���ֽ�  
            sheet.setDefaultColumnWidth(20);
            // ���һ����ʽ  
            HSSFCellStyle style = workbook.createCellStyle();
            // ���ñ�����ʽ  
            style = ExcelStyle.setHeadStyle(workbook, style);
            // �õ������ֶ�  
            Field filed[] = tObject.getClass().getDeclaredFields();
            // ����  
            List<String> exportfieldtile = new ArrayList<String>();
            // �������ֶε�get����  
            List<Method> methodObj = new ArrayList<Method>();
            // �������filed  
            for (int i = 0; i < filed.length; i++) {
                Field field = filed[i];
                ExcelAnnotation excelAnnotation = field.getAnnotation(ExcelAnnotation.class);
                // ���������annottion  
                if (excelAnnotation != null) {
                    String exprot = excelAnnotation.exportName();
                    // ��ӵ�����  
                    exportfieldtile.add(exprot);
                    // ��ӵ���Ҫ�������ֶεķ���  
                    String fieldname = field.getName();
                    String getMethodName = "get" + fieldname.substring(0, 1).toUpperCase() + fieldname.substring(1);
                    Method getMethod = clazz.getMethod(getMethodName, new Class[]{});
                    methodObj.add(getMethod);
                }
            }

            // �����������  
            HSSFRow row = sheet.createRow(0);
            for (int i = 0; i < exportfieldtile.size(); i++) {
                HSSFCell cell = row.createCell(i);
                cell.setCellStyle(style);
                HSSFRichTextString text = new HSSFRichTextString(exportfieldtile.get(i));
                cell.setCellValue(text);
            }

            // ѭ���������  
            int index = 0;
            iterator = dataset.iterator();
            while (iterator.hasNext()) {
                //�ӵڶ��п�ʼд����һ���Ǳ���  
                index++;
                row = sheet.createRow(index);
                T t = (T) iterator.next();
                for (int k = 0; k < methodObj.size(); k++) {
                    HSSFCell cell = row.createCell(k);
                    Method getMethod = methodObj.get(k);
                    Object value = getMethod.invoke(t, new Object[]{});
                    String textValue = getValue(value);
                    cell.setCellValue(textValue);
                }
            }
            workbook.write(out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getValue(Object value) {
        String textValue = "";
        if (value == null) {
            return textValue;
        }
        if (value instanceof Boolean) {
            boolean bValue = (Boolean) value;
            textValue = "��";
            if (!bValue) {
                textValue = "��";
            }
        } else if (value instanceof Date) {
            Date date = (Date) value;
            textValue = sdf.format(date);

        } else {
            textValue = value.toString();
        }
        return textValue;
    }

    public static void main(String[] args) throws IOException {
        List<OdsTable> list1 = null;
        OutputStream out = new FileOutputStream("D:\\testOne1.xls");
        ExcelExport<OdsTable> ex = new ExcelExport<OdsTable>();
//        ImportExcel<TestVo> test = new ImportExcel<TestVo>(TestVo.class);
//        File file = new File("D:\\testOne.xls");
//        List<TestVo> results = (List<TestVo>) test.importExcel(file);
        Session session = null;
        Query query = null;
        session = (Session) HibernateUtil.getSessionFactory().getCurrentSession();
        String hql = null;
        Transaction tx = session.beginTransaction();
        hql = "from OdsTable as a where a.dataSourceId='12'";
        query = session.createQuery(hql);
        list1 = query.list();
        tx.commit();
        ex.exportExcel("����", list1, out);
        out.close();
    }
}
